package com.wanlian.socketserver.Device.worker;

import com.wanlian.json.JsonStringUtil;
import com.wanlian.netty.model.Address;
import com.wanlian.netty.msg.Device.DiskGetRequest;
import com.wanlian.netty.msg.Device.model.Disk;
import com.wanlian.netty.msg.MsgType;
import com.wanlian.netty.msg.PeerMsg;
import com.wanlian.util.HttpUtils;

import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 用户磁盘获取类
 */
public class DeviceShareSizeWorker {

    /**
     * 定时获取所有路由器共享设置
     */
    public static void work() {
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            fixedThreadPool.execute(new Runnable() {
                public void run() {
                    while (true) {
                        try {
                            TimeUnit.MILLISECONDS.sleep(5 * 60 * 1000);
                            sendRouterShareSize();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
    }

    //发送
    public static synchronized void sendRouterShareSize() {
        Map<String, Address> allRouters = DeviceServerWorker.sessionPool.getAllRouter();
        for (String deyKey : allRouters.keySet()) {
            DiskGetRequest diskGetRequest = new DiskGetRequest();
            diskGetRequest.setClientId(DeviceServerWorker.getServer().getPublicKey());
            diskGetRequest.setTagClientId(deyKey);
            DeviceServerWorker.sendDataByKey(deyKey, diskGetRequest);
        }
    }

    //调整用户的共享空间
    public static void tidyDeviceShareSize(PeerMsg peerMsg) {
        String msgType = peerMsg.getBaseMsg().getType();
        if (msgType.equals(MsgType.DEVICE_DISKGET_REP)) {
            Disk disk = JsonStringUtil.readValue(peerMsg.getBaseMsg().getContent(), Disk.class);
            disk.setDevicekey(peerMsg.getBaseMsg().getClientId());
            HttpUtils.sendPost("http://localhost:8080/wanlian.candy/device/dsharesize", JsonStringUtil.writeValueAsString(disk));
        }
    }

}
